package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import dao.dao.impl.DaoFactory;
public class DynamicProxy {
	private DynamicProxy(){}
	@SuppressWarnings("unchecked")
	public static <T> T creatServiceProxy(Class<T> serviceInterfaceClass,Class<?>serviceImpClass) throws Exception{
		try {
			Object target=serviceImpClass.newInstance();
			return (T) 
				Proxy.newProxyInstance(
					serviceInterfaceClass.getClassLoader(), 
					new Class<?>[]{serviceInterfaceClass},
					new InvocationHandler(){
						public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
							try{
								DaoFactory.getCurrDao();
								Object result=method.invoke(target, args);
								DaoFactory.commitCurrTx();
								return result;
							}catch(Exception e){
								e.printStackTrace();
								DaoFactory.rollbackCurrTx();
								throw e;
							}
						}
					}
				);
		} catch (RuntimeException e) {
			throw new RuntimeException(e);
		}
	}
}
